package thread;
/**
 * 同步块
 * 有效的缩小同步范围可以在保证并发安全的前提下尽可能的提高并发效率。
 *
 * 同步块语法:
 * synchronized(同步监视器对象){
 *     需要多个线程同步执行的代码片段
 * }
 */
public class Synchronized2 {
    public static void main(String[] args) {
        Shop shop = new Shop();
        Thread t1 = new Thread("创奇"){
            @Override
            public void run() {
                shop.buy1();
            }
        };

        Thread t2 = new Thread("克金"){
            @Override
            public void run() {
                shop.buy2();
            }
        };

        t1.start();
        t2.start();
    }
}

class Shop{
    public void buy1(){

        try {
            Thread t = Thread.currentThread();
            System.out.println(t.getName()+":在挑衣服");
            Thread.sleep(3000);
            synchronized (this){
                System.out.println(t.getName()+":在试衣服");
                Thread.sleep(3000);
            }
            System.out.println(t.getName()+":离开");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void buy2(){
        try {
            Thread t = Thread.currentThread();
            System.out.println(t.getName()+":在挑衣服");
            Thread.sleep(3000);
            synchronized (this){
                System.out.println(t.getName()+":在试衣服");
                Thread.sleep(3000);
            }
            System.out.println(t.getName()+":离开");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
